# coding:utf-8

from bson import ObjectId
import tornado
from tornado import gen
from tornado.web import HTTPError

from handler.api import errors
from handler.api.base import BaseHandler

import config
from data.redis import redis
from data.mongo import col_samples_01,col_vibration_leve,col_max_acceleration,col_event,col_event_data

import datetime
import json
import struct
# from data.collections import User, School
#from util.token import token_manager
class ConfigHandler(BaseHandler):
    def get(self):
        # 读取配置
        with open('service_config.json', 'r') as f:
            config = f.read()
        service_config = json.loads(config)
        data_json={
                    "peak_limit":float(service_config["peak_limit"]),\
                    "vibration_limit_1":int(service_config["vibraiton_limit_1"]),\
                    "vibration_limit_2":int(service_config["vibraiton_limit_2"])\
                    }
        self.write_json(data_json)
 
class SensorListHandler(BaseHandler):
    def get(self):
    
        # 读取配置
        with open('service_config.json', 'r') as f:
            config = f.read()
        service_config = json.loads(config)
        GateWayList=service_config["GateWayList"]
        
        sensorList=[]
        
        for item in GateWayList:
            j=0
            for i in item["ConnectList"]:
                j+=1
                if i == 1:
                    #传感器编号
                    sensorID=item["GateWayID"]+"_0"+str(j)
            
                    # redis_last_vibration_leve_time_key = "last_vibration_time_01D9A057_01"
                    # redis_last_time=""
                    # #redis_last_time = redis.lrange(redis_last_vibration_leve_time_key,0,4)[3]
                    #samples_co_name="samples_"+sensorID
                    #samples_last=col_samples_01["samples_co_name"].find().sort([("samples_time",-1)]).limit(1)#[0]["samples_time"]
                    
                    redis_last_time=""
                    #samples_time_key="last_time_samples_" + sensorID[0:-3]
                    samples_time_key="last_second_samples_" + sensorID
                    #redis_last_time=redis.get(samples_time_key)
                    #print(json.loads(redis.lrange(samples_time_key,0,1)[0])["samples_time"])
                    redis_last_time_list=redis.lrange(samples_time_key,0,1)
                    if len(redis_last_time_list) > 0:
                        redis_last_time=json.loads(redis.lrange(samples_time_key,0,1)[0])["samples_time"]
                    # for samples_item in samples_last:
                        # redis_last_time=samples_item["samples_time"]
                    peakLimitCount=col_event.find({"sensorID":sensorID,"eventType":1}).count()
                    vibrationLimit1=col_event.find({"sensorID":sensorID,"eventType":2}).count()
                    vibrationLimit2=col_event.find({"sensorID":sensorID,"eventType":3}).count()
                    item1={"sensorID":sensorID,\
                             "peakLimitCount":peakLimitCount,\
                             "vibrationLimit1":vibrationLimit1,\
                             "vibrationLimit2":vibrationLimit2,\
                             "lastCollectTime":redis_last_time}
                    sensorList.append(item1)
        data_json = {"sensors":sensorList}
        self.write_json(data_json)

class MonitorHandler(BaseHandler):
    def get(self):
        sensorID = self.get_argument('sensorID')
        smples_data = redis.lrange(sensorID,0,-1)
        data_length=len(smples_data)
        current=datetime.datetime.now()
        samples_time=[]
        for i in range(data_length):
            samples_time.append( (current - datetime.timedelta(seconds=(0.0005*i))) )
        samples_time.append(current)
        data_json = {"sensorID":sensorID,"smples_data":smples_data,"samples_time":samples_time}
        self.write_json(data_json)

    def post(self):
        sensorID = self.get_argument('sensorID')
        smples_data=[]
        samples_time=[]
        samples_data_key="last_second_samples_" + sensorID
        
        smples_data_list=redis.lrange(samples_data_key,-1,-1)
        #print(smples_data_list[0])
        smples_data_json=json.loads(smples_data_list[0])
        samples_time.append(smples_data_json['samples_time'])
        smples_data_1_str_list=smples_data_json['data']
        
        #samples_time_key="last_time_samples_" + sensorID[0:-3]
        #print(samples_time_key)
        
        # last_second_samples_length=redis.llen(samples_data_key)    
        # smples_data_list=[]        
        # smples_data_list=redis.lrange(samples_data_key,-1,-1)
        # smples_data_1_str_list=smples_data_list[0].split(',')
        # #smples_data_2_str_list=smples_data_list[1].split(', ')
        # #smples_data_3_str_list=smples_data_list[2].split(', ')
        # #smples_data_str_list=smples_data_1_str_list+smples_data_2_str_list+smples_data_3_str_list[0:int(len(smples_data_3_str_list)/2)]
        smples_data=list(map(lambda x:float(x),smples_data_1_str_list))
        
        # samples_time.append(redis.get(samples_time_key))
        data_json = {"sensorID":sensorID,"smples_data":smples_data,"samples_time":samples_time}
        self.write_json(data_json)

class RealTimeVibrationLeveHandler(BaseHandler):
    def get(self):
        sensorID = self.get_argument('sensorID')
        samples_data_key = "last_second_vibration_level_" + sensorID
        #samples_time_key = "last_time_vibration_leve_samples_" + sensorID
        
        redis_last_vibration_leve_time=[]
        redis_last_vibration_leve_data=[]
        
        samples_data=json.loads(redis.get(samples_data_key))
        redis_last_vibration_leve_time.append(samples_data['samples_time'])
        redis_last_vibration_leve_data = list(map(lambda x:x['vibration_leve'],samples_data['data']))
        #print(redis_last_vibration_leve_data)
        #print(samples_data['samples_time'])
        
        # last_second_vibration_leve_length=redis.llen(samples_data_key)
        # redis_last_vibration_leve_data = redis.lrange(samples_data_key,0,int(last_second_vibration_leve_length/2)-1)
        # redis_last_vibration_leve_data = list(map(lambda x:float(x),redis_last_vibration_leve_data))
        # redis_last_vibration_leve_time.append(redis.get(samples_time_key))
        
        data_json = {"vibrationLeveList":[{"time":redis_last_vibration_leve_time},
                                          {"data":redis_last_vibration_leve_data}]}
        self.write_json(data_json)
        
class EventListHandler(BaseHandler):
    def get(self):
        sensorID = self.get_argument('sensorID')
        peakLimit = self.get_argument('peakLimit_1')
        limit_1 = self.get_argument('limit_1')
        limit_2 = self.get_argument('limit_2')
        limit_3 = self.get_argument('limit_3')
        
        limit = self.get_argument('limit')
        offset = self.get_argument('offset')
        #print(limit)
        #print(offset)
        
        event_data=col_event.find({"sensorID":sensorID,'time_dif':{"$gte":int(limit_3)},'$or':[{'eventType':int(peakLimit)},{'eventType':int(limit_1)},{'eventType':int(limit_2)}]},{"_id":0}).sort([("eventStartTime",-1)]).limit(int(limit)).skip(int(offset))
        event_data_count=col_event.find({"sensorID":sensorID,'time_dif':{"$gte":int(limit_3)},'$or':[{'eventType':int(peakLimit)},{'eventType':int(limit_1)},{'eventType':int(limit_2)}]},{"_id":0}).sort([("eventStartTime",-1)]).count()
        #print(event_data_count)
        #print(event_data)
        event_list=[]
        for item in event_data:
            event_list.append(item)
        data_json = {"eventList":event_list,"total":event_data_count}
        self.write_json(data_json)
        
class TimeHistoryHandler(BaseHandler):
    def get(self):
        #print(datetime.datetime.now())
        sensorID = self.get_argument('sensorID')
        startTime = self.get_argument('startTime')
        eventNum = self.get_argument('eventNum')
        # endTime = self.get_argument('endTime')
        # time_startTime=datetime.datetime.strptime(startTime,'%Y-%m-%d %H:%M:%S.%f')
        # time_endTime=datetime.datetime.strptime(endTime,'%Y-%m-%d %H:%M:%S.%f')
        # time_startTime_02=time_startTime+datetime.timedelta(seconds=-1)
        # time_endTime_02=time_endTime+datetime.timedelta(seconds=1)
        # startTime=time_startTime_02.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
        # endTime=time_endTime_02.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
        #print(startTime)
        #print(endTime)
        # samples_co_name="samples_"+sensorID
        
        # samples_data=col_samples_01[samples_co_name].find({"samples_time":{"$gte":startTime,"$lte":endTime}}).sort([("samples_time",1)]).batch_size(500)
        
        #print("---------------------------")
        #print(eventNum)
        samples_data=col_event_data.find({"sensorID":sensorID,"eventNum":eventNum}).sort([("order_number",1)])#.limit(1)#"eventStartTime":startTime,.sort([("samples_time",1)])#
        time_list=[]
        data_list=[]
        str_item=''
        for item_2 in samples_data:
            data_list=data_list + item_2['data']
            str_item=item_2["eventStartTime_1"]
        #print(str_item)
        start_time=datetime.datetime.strptime(str_item,'%Y-%m-%d %H:%M:%S.%f')
        samples_data.close()  
        for j in range(len(data_list)):
            sing_time=start_time+datetime.timedelta(seconds=0.0005*j)
            sing_time_str=sing_time.strftime("%Y-%m-%d %H:%M:%S.%f")[0:23]
            time_list.append(sing_time_str)
            
        #print(datetime.datetime.now())
        
        # time_list_0=[]
        # data_list_0=[]
        # item_count=0
        # samples_data_list=list(samples_data[:])
        # print(datetime.datetime.now())
        # for item in samples_data:
            # item_count=item_count+1
            # data_list_0+=item["data"]
            # #time_list_0.append(item["samples_time"]+'.0')
        # print(item_count)
        # #print(time_list_0[0])
        # #print(data_list_0)
        # print(datetime.datetime.now())
        
        
        # time_list=[]
        # data_list=[]
        # for item in samples_data:
            # sing_02_data=item["data"]
            # #sing_02_length=len(sing_02_data)
            # str_item=item["samples_time"]+'.0'
            # start_time=datetime.datetime.strptime(str_item,'%Y-%m-%d %H:%M:%S.%f')
            # for i in range(len(sing_02_data)):
                # data_list.append(float(sing_02_data[i]))
                # #if i==0 or i==(sing_02_length-1):
                # #time_list.append(item["samples_time"])
                # #else:
                # #    time_list.append("")
                # sing_time=start_time+datetime.timedelta(seconds=0.002*i)
                # sing_time_str=sing_time.strftime("%Y-%m-%d %H:%M:%S.%f")[0:23]
                # time_list.append(sing_time_str)
            
        data_json = {"vibrationLeveList":[{"time":time_list},
                                          {"data":data_list}]}
        #print(datetime.datetime.now())
        self.write_json(data_json)

class EventVibrationLeveHandler(BaseHandler):
    def get(self):
        #print(datetime.datetime.now())
        sensorID = self.get_argument('sensorID')
        eventNum = self.get_argument('eventNum')
        #startTime = self.get_argument('StartTime')
        #endTime = self.get_argument('EndTime')

        samples_data=col_event_data.find({"sensorID":sensorID,"eventNum":eventNum}).sort([("order_number",1)])#.limit(1)#"eventStartTime":startTime,
        str_item=''
        data_list_num=0
        for item_2 in samples_data:
            startTime=item_2["eventStartTime_1"]
            data_list_num=data_list_num + len(item_2['data'])
        str_item=startTime
        start_time=datetime.datetime.strptime(str_item,'%Y-%m-%d %H:%M:%S.%f')
        samples_data.close()
        end_time=start_time+datetime.timedelta(seconds=0.0005*data_list_num)
        endTime=end_time.strftime("%Y-%m-%d %H:%M:%S.%f")[0:23]
        
        print(start_time)
        print(endTime)

        vibration_leve_co_name="vibration_leve_"+sensorID
        
        vibration_leve_data=col_vibration_leve[vibration_leve_co_name].find({"samples_time":{"$gte":startTime,"$lte":endTime}}).sort([("samples_time",1)])
        print(vibration_leve_co_name)
        time_list=[]
        data_list=[]
        str_item=''
        for item_2 in vibration_leve_data:
            data_list.append(item_2['vibration_leve'])
            time_list.append(item_2["samples_time"])
        vibration_leve_data.close() 
        print(len(data_list))
        data_json = {"vibrationLeveList":[{"time":time_list},
                                          {"data":data_list}]}
        #print(time_list)
        #print(data_list)
        self.write_json(data_json)
        
class OverrunHandler(BaseHandler):
    def get(self):
        sensorId = self.get_argument('sensorId')
        startTime = self.get_argument('startTime').replace('T',' ')+':00.0'
        endTime = self.get_argument('endTime').replace('T',' ')+':00.0'
        limit_Z = self.get_argument('limit_Z')
        print(sensorId)
        print(startTime)
        print(type(startTime))
        print(endTime)
        print(limit_Z)

        vibration_leve_co_name="vibration_leve_"+sensorId        
        overrun_num=col_vibration_leve[vibration_leve_co_name].find({"samples_time":{"$gte":startTime,"$lte":endTime},"vibration_leve":{"$gte":float(limit_Z)}}).count()
        overrun_all=col_vibration_leve[vibration_leve_co_name].find({"samples_time":{"$gte":startTime,"$lte":endTime}}).count()
        overrun_result=0.0
        if overrun_all > 0:
            overrun_result = round(overrun_num/overrun_all,4)
        data_json={
                    "overrun_result":overrun_result,\
                    "overrun_num":overrun_num,\
                    "overrun_all":overrun_all\
                    }
        self.write_json(data_json)


